import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/index'
  },
  {
    path: '/index',
    name: 'index',
    component: () => import('@/views/index')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login')
  },
  {
    path: '/sign',
    name: 'sign',
    component: () => import('@/views/sign')
  }, {
    path: '/addShop',
    name: 'addShop',
    component: () => import('@/views/addShop')
  },
  {
    path: '/admin',
    name: 'admin',
    component: () => import('@/views/admin/admin'),
    redirect: { name: 'AdIndex' },
    children: [
      {
        path: '/AdIndex',
        name: 'AdIndex',
        component: () => import('@/views/admin/AdIndex')
      },
      {
        path: '/AdList',
        name: 'AdList',
        component: () => import('@/views/admin/AdList')
      }
    ]
  },
  {
    path: '/shop',
    name: 'shop',
    component: () => import('@/views/shop/shop'),
    redirect: { name: 'shopIndex' },
    children: [
      {
        path: '/shopIndex',
        name: 'shopIndex',
        component: () => import('@/views/shop/shopIndex')
      }, {
        path: '/shopAdd',
        name: 'shopAdd',
        component: () => import('@/views/shop/shopAdd')
      }, {
        path: '/shopList',
        name: 'shopList',
        component: () => import('@/views/shop/shopList')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  if (to.path === '/index') return next()
  if (to.path === '/') return next()
  if (to.path === '/sign') return next()
  const token = sessionStorage.getItem('token')
  if (!token) return next('/login')
  next()
})

export default router
